<template>
    <el-table ref="tableDataRef" :data="tableData" v-loading="loading" @selection-change="handleSelectionChange"
        row-key="userId" :highlight-current-row="true" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" label="姓名" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="phonenumber" label="手机号" />
    </el-table>
</template>

<script setup>
import { getPoliceAssistantListApi } from "@/api/Police.js";
import { useTemplateRef } from "vue";

const { moreChoose, uses } = defineProps({
    uses: {
        type: Object || Array
    },
    moreChoose: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:uses'])
const loading = ref(false)
const tableData = ref([])
const tableDataRef = useTemplateRef('tableDataRef')
// 有效用户 ID 列表
const validUser = ref([])

// 获取法警列表
const getPoliceList = async () => {
    loading.value = true
    const res = await getPoliceAssistantListApi();
    tableData.value = res.data
    loading.value = false
}

onMounted(() => {
    getPoliceList()
        .then(() => {
            validUser.value = [];
            syncSelectedRows(); // 等待数据加载完成后再同步已选数据
        });
})

// 部门列表选择数据
const handleSelectionChange = (data) => {
    // console.log('table 选择框事件数据：', data)
    emit('update:uses', data)
}

// 同步 table 选中数据
const syncSelectedRows = (data) => {
    // console.log('校验当前 tabel 是否有选中的数据:', tableDataRef.value.getSelectionRows())
    if (tableDataRef.value) {

        if (Object.keys(uses).length <= 0) {
            tableDataRef.value.clearSelection();
            return '';
        }

        if (Object.keys(uses).length) {
            uses.forEach(item => {
                const selectedRow = tableData.value.find(row => row.userId === Number(item.userId));
                if (selectedRow) {
                    // 添加有效的用户，后续进行曝光处理
                    validUser.value.push(selectedRow)
                    // console.log('有选择条件，进行选择', selectedRow)
                    tableDataRef.value.toggleRowSelection(selectedRow, true);
                }
            });

            emit('update:uses', validUser.value)
        }
    }
};
</script>

<style scoped lang="scss"></style>